#include <libxml/SAX.h>
#include <sys/param.h>
#include <string.h>
#include <stdbool.h>
#include <curl/curl.h>
#include "curl_sax.h"
#include "config.h"


size_t curl_sax_callback(void *ptr, size_t size, size_t nmemb, void *data) {
  CurlData *curlData = (CurlData *)data;

  if (! curlData->ctx)
    curlData->ctx = xmlCreatePushParserCtxt(curlData->sax_handler, 
					    curlData->xml_user_data, 
					    ptr, nmemb, NULL);

  xmlParseChunk(curlData->ctx, ptr, nmemb, 0);

  return nmemb;
}



int curl_sax_get_attribute(char *name, char *dest, size_t max, int nb_attributes, const xmlChar **attributes) {

  int index;

  for (index = 0; index < nb_attributes * 5; index += 5) 
    if (! strcmp(name, attributes[ATTRIBUTE_KEY(index)])) {
      memset(dest, 0, max);
      memcpy(dest, 
	     attributes[ATTRIBUTE_VALUE_START(index)],
	     MIN(attributes[ATTRIBUTE_VALUE_END(index)] - attributes[ATTRIBUTE_VALUE_START(index)], max - 1));
      return 1;
    }

  return 0;
}

int curl_sax_get_data(const char *url, xmlSAXHandler *saxHandler, void *userData) {

  CurlData data;
  CURL *curl_handle = NULL;

  memset(&data, 0, sizeof(data));
  data.xml_user_data = userData;
  data.sax_handler = saxHandler;

  curl_handle = curl_easy_init();
  curl_easy_setopt(curl_handle, CURLOPT_URL, url);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, curl_sax_callback);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &data);
  curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, USER_AGENT);
  curl_easy_setopt(curl_handle, CURLOPT_NETRC, NETRC);
  curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, VERIFYPEER);

  /* One of those set buggy mode to false situations.
     Apparently if curl is being used in a multi threaded way
     This flag needs to be set to 1 */
  curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1);

  curl_easy_perform(curl_handle);

  xmlFreeParserCtxt(data.ctx);
  curl_easy_cleanup(curl_handle);

  return 1;
}
